package com.anolesoft.twelvePlan.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.twelvePlan.dto.MesGyInfoExport;
import com.anolesoft.twelvePlan.dto.MesWXInfoExport;
import com.anolesoft.twelvePlan.entity.MesGyInfoDO;
import com.anolesoft.twelvePlan.entity.MesWxInfoDO;
import com.anolesoft.twelvePlan.mapper.MesWXInfoMapper;
import com.anolesoft.twelvePlan.service.MesGyInfoService;
import com.anolesoft.twelvePlan.service.MesWXInfoService;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zyq
 * @date 2022/5/15
 */
@Slf4j
public class MesWxInfoListener implements ReadListener<MesWXInfoExport> {
    private static final int BATCH_COUNT = 1000;

    private List<MesWXInfoExport> list = new ArrayList<>();

    private List<MesWxInfoDO> communityList = new ArrayList<>(BATCH_COUNT);

    private MesWXInfoService mesWXInfoService;

    public MesWxInfoListener(MesWXInfoService mesWXInfoService){
        this.mesWXInfoService = mesWXInfoService;
    }

    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {

    }

    @Override
    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {

    }

    @Override
    public void invoke(MesWXInfoExport mesWXInfoExport, AnalysisContext analysisContext) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesWxInfoDO mesWxInfoDO =  BeanUtil.copyProperties(mesWXInfoExport, MesWxInfoDO.class);
        mesWxInfoDO.setCreateuid(loginUser.getEmpUid());
        mesWxInfoDO.setFactoryId(loginUser.getFacCode());
        log.debug("数据：{}", mesWxInfoDO);
        communityList.add(mesWxInfoDO);
        if (communityList.size() >= BATCH_COUNT) {
            batchInsert();
            // 存储完成清理 list
            communityList.clear();
        }
    }

    @Override
    public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        batchInsert();
    }

    /*
     * 重写此方法时默认返回false 需改成true
     */
    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return true;
    }

    void batchInsert(){
        log.debug("数据：{}", communityList);
        mesWXInfoService.uploadWXInfo(communityList);
    }
}
